package com.apex.sdk.ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.apex.bluetooth.callback.GeneralCallback;
import com.apex.bluetooth.callback.OtaCallback;
import com.apex.bluetooth.core.EABleManager;
import com.apex.bluetooth.enumeration.EABleConnectState;
import com.apex.bluetooth.utils.LogUtils;
import com.apex.lie_sheng_jie.watcha.JieliDialCallback;
import com.apex.lie_sheng_jie.watcha.JieliWatchFaceManager;
import com.apex.lie_sheng_jie.watcha.JieliWatchInfo;
import com.apex.sdk.R;
import com.apex.sdk.databinding.ActivityJieliDialBinding;
import com.apex.sdk.dialog.WaitingDialog;
import com.jieli.jl_rcsp.model.base.BaseError;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

public class JieliDialActivity extends AppCompatActivity {
    private final String TAG = this.getClass().getSimpleName();
    private WaitingDialog waitingDialog;
    private ActivityJieliDialBinding activityJieliDialBinding;
    JieliDialAdapter jieliDialAdapter;
    List<JieliWatchInfo> infos;
    Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x40) {
                if (waitingDialog != null) {
                    if (waitingDialog.isShowing()) {
                        waitingDialog.dismiss();
                    }
                }
                //  if (jieliDialAdapter != null && infos != null && !infos.isEmpty()) {
                jieliDialAdapter.notifyDataSetChanged();
                //  }
            } else if (msg.what == 0x41) {
                if (waitingDialog != null) {
                    if (waitingDialog.isShowing()) {
                        waitingDialog.dismiss();
                    }
                }
                Toast.makeText(JieliDialActivity.this, getString(R.string.failed_to_get_data), Toast.LENGTH_SHORT).show();
            } else if (msg.what == 0x43) {
                if (waitingDialog != null) {
                    if (waitingDialog.isShowing()) {
                        waitingDialog.dismiss();
                    }
                }
                Toast.makeText(JieliDialActivity.this, getString(R.string.ota_failed), Toast.LENGTH_SHORT).show();
            } else if (msg.what == 0x42) {
                if (waitingDialog != null) {
                    if (waitingDialog.isShowing()) {
                        waitingDialog.dismiss();
                    }
                }
                Toast.makeText(JieliDialActivity.this, getString(R.string.ota_success), Toast.LENGTH_SHORT).show();
            } else if (msg.what == 0x44) {
                if (waitingDialog != null) {
                    if (waitingDialog.isShowing()) {
                        waitingDialog.dismiss();
                    }
                }
                Toast.makeText(JieliDialActivity.this, getString(R.string.delete_fail), Toast.LENGTH_SHORT).show();
            } else if (msg.what == 0x45) {
                if (waitingDialog != null) {
                    if (waitingDialog.isShowing()) {
                        waitingDialog.dismiss();
                    }
                }
                Toast.makeText(JieliDialActivity.this, getString(R.string.modification_failed), Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityJieliDialBinding = ActivityJieliDialBinding.inflate(getLayoutInflater());
        setContentView(activityJieliDialBinding.getRoot());
        activityJieliDialBinding.tool.setNavigationIcon(R.mipmap.exit_page);
        setSupportActionBar(activityJieliDialBinding.tool);
        getSupportActionBar().setTitle(null);
        activityJieliDialBinding.tool.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(JieliDialActivity.this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        activityJieliDialBinding.dialList.setLayoutManager(linearLayoutManager);
        jieliDialAdapter = new JieliDialAdapter();
        activityJieliDialBinding.dialList.setAdapter(jieliDialAdapter);
        EABleConnectState state = EABleManager.getInstance().getDeviceConnectState();
        if (state == EABleConnectState.STATE_CONNECTED) {
            if (waitingDialog == null) {
                waitingDialog = new WaitingDialog(JieliDialActivity.this);
            }
            waitingDialog.show();
            queryDial();

        }
        activityJieliDialBinding.updateDial.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EABleConnectState state = EABleManager.getInstance().getDeviceConnectState();
                if (state == EABleConnectState.STATE_CONNECTED) {
                    if (waitingDialog == null) {
                        waitingDialog = new WaitingDialog(JieliDialActivity.this);
                    }
                    waitingDialog.show();
                    new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            try {
                                //获取表盘
                                InputStream inputStream = getAssets().open("watch21");
                                String filePath3 = save2File(inputStream, "123456789");
                                JieliWatchFaceManager.getInstance().addWatchFace(filePath3, new OtaCallback() {

                                    @Override
                                    public void success() {
                                        queryDial();
                                    }

                                    @Override
                                    public void progress(int i) {
                                        LogUtils.e(TAG, "当前进度:" + i + "%");
                                    }

                                    @Override
                                    public void mutualFail(int i) {
                                        LogUtils.e(TAG, "失败");
                                        if (mHandler != null) {
                                            mHandler.sendEmptyMessage(0x43);
                                        }
                                    }
                                });
                            } catch (Exception e) {
                                e.printStackTrace();
                                if (mHandler != null) {
                                    mHandler.sendEmptyMessage(0x45);
                                }
                            }
                        }
                    }.start();

                }
            }
        });
    }

    class JieliDialAdapter extends RecyclerView.Adapter<JieliDialAdapter.JieliDialHold> {

        @NonNull
        @Override
        public JieliDialHold onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View childView = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_jieli_dial, parent, false);
            return new JieliDialHold(childView);
        }

        @Override
        public void onBindViewHolder(@NonNull JieliDialHold holder, int position) {
            if (infos == null || infos.isEmpty()) {
                return;
            }
            final JieliWatchInfo jieliWatchInfo = infos.get(position);
            holder.nameView.setText(jieliWatchInfo.name);

        }

        @Override
        public int getItemCount() {
            return infos == null ? 0 : infos.size();
        }

        class JieliDialHold extends RecyclerView.ViewHolder {
            TextView nameView;

            public JieliDialHold(@NonNull View itemView) {
                super(itemView);
                nameView = itemView.findViewById(R.id.dialName);
            }
        }
    }

    private void queryDial() {
        JieliWatchFaceManager.getInstance().getDialList(new JieliDialCallback() {
            @Override
            public void jieliDial(List<JieliWatchInfo> list) {
                infos = list;
                if (mHandler != null) {
                    mHandler.sendEmptyMessage(0x40);
                }

            }

            @Override
            public void error(BaseError baseError) {
                if (mHandler != null) {
                    mHandler.sendEmptyMessage(0x41);
                }

            }
        });
    }

    private String save2File(InputStream inputStream, String fName) {

        try {
            File file = new File(getExternalCacheDir(), fName);
            if (!file.exists()) {
                file.createNewFile();
            }
            OutputStream os = new FileOutputStream(file);
            int read = 0;
            byte[] bytes = new byte[1024 * 1024];
            //先读后写
            while ((read = inputStream.read(bytes)) > 0) {
                byte[] wBytes = new byte[read];
                System.arraycopy(bytes, 0, wBytes, 0, read);
                os.write(wBytes);
            }
            os.flush();
            os.close();
            inputStream.close();
            return file.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onDestroy() {
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        if (waitingDialog != null) {
            waitingDialog.dismiss();
            waitingDialog = null;
        }
        super.onDestroy();
    }
}
